package com.zznzzn.myweb.controller;


import com.zznzzn.myweb.pojo.RespModel;
import com.zznzzn.myweb.pojo.User;
import com.zznzzn.myweb.service.FileService;
import com.zznzzn.myweb.service.UserService;
import com.zznzzn.myweb.util.Base64Util;
import com.zznzzn.myweb.util.JWTUtil;
import com.zznzzn.myweb.util.RespHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private UserService userService;


    @PostMapping("/upload/avatar/{color}")
    public RespModel<Object> uploadAvatar(
            @RequestParam("file") MultipartFile multipartFile,
            @PathVariable("color") String color,
            HttpServletRequest request
    ){
        String uuid = JWTUtil.getUserId(request.getHeader(JWTUtil.AUTH_HEADER_KEY));

        Map<String,Object> res = new HashMap<>();
        if (multipartFile != null){
            String filePath = null;
            String oldFile = null;
            try {
                oldFile = userService.getUserById(uuid).getAvatarpath();
                filePath = fileService.receiveAvatar(multipartFile, 200);

                fileService.setAvatar(uuid,filePath,color);
                fileService.deleteLocalFile(oldFile,true);
            } catch (Exception e) {
                RespHelper.buildFailure(e.getMessage());
            }
            res.put("filepath",filePath);
            res.put("color",color);
        }

        return RespHelper.buildSuccess("更改头像成功",res);
    }


}
